/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[StudentDaoJdbcImpl.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package mvc.dao.impl;

import java.util.List;

import mvc.dao.IStudentDao;
import mvc.dao.StudentCriteria;
import mvc.domain.Student;
import mvc.utils.DaoUtils;

/**
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class StudentDaoJdbcImpl extends DaoUtils<Student> implements IStudentDao {

	/**
	 * 查询所有学生
	 */
	@Override
	public List<Student> findAllStudents() {
		String sql = "SELECT id, name, age, gender, birthday FROM Student";
		return this.getAll(sql);
	}

	/**
	 * 查找符合条件的学生记录
	 * 
	 * @param criteria
	 * @return
	 */
	@Override
	public List<Student> findStudentsByCriteria(StudentCriteria criteria) {
		String sql = "SELECT id, name, age, gender, birthday FROM Student WHERE name LIKE ? AND gender LIKE ?";
		return this.getAll(sql, criteria.getName(), criteria.getGender());
	}

	/**
	 * 查找指定ID的学生
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public Student findStudentById(Integer id) {
		String sql = "SELECT id, name, age, gender, birthday FROM Student WHERE id = ?";
		return this.uniqueResult(sql, id);
	}

	/**
	 * 保存新的学生记录
	 * 
	 * @param student
	 */
	@Override
	public void save(Student student) {
		String sql = "INSERT INTO Student(name, age, gender, birthday) VALUES(?, ?, ?, ?)";
		Object[] parameters = { student.getName(), student.getAge(), student.getGender(), student.getBirthday() };
		this.update(sql, parameters);
	}

	/**
	 * 根据ID更新学生记录
	 * 
	 * @param student
	 */
	@Override
	public void update(Student student) {
		String sql = "UPDATE Student SET name = ?, age = ?, gender = ?, birthday = ? WHERE id = ?";
		Object[] parameters = { student.getName(), student.getAge(), student.getGender(), student.getBirthday(),
				student.getId() };
		this.update(sql, parameters);
	}

	/**
	 * 根据ID删除学生记录
	 * 
	 * @param id
	 */
	@Override
	public void delete(Integer id) {
		String sql = "DELETE FROM Student WHERE id = ?";
		this.update(sql, id);
	}

	/**
	 * 获得指定名字的学生的记录数, 用于新增学生记录是判断名字是否重复
	 */
	@Override
	public int getStudentCountByName(String name) {
		String sql = "SELECT COUNT(*) FROM Student WHERE name = ?";
		return ((Long) this.getSingleColumn(sql, name)).intValue();
	}
}
